package com.jic.point.controller.feign;

import com.github.pagehelper.PageInfo;
import com.jic.common.base.vo.RestResult;
import com.jic.point.api.HaierPointQueryApi;
import com.jic.point.manage.request.ConfApiAuthorityApplyRequest;
import com.jic.point.model.entity.PublMemberLog;
import com.jic.point.model.entity.*;
import com.jic.point.model.vo.response.PublMemberBalanceResponse;
import com.jic.point.rest.request.*;
import com.jic.point.rest.response.*;
import com.jic.point.service.*;
import io.swagger.annotations.Api;
import org.springframework.beans.BeanUtils;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;


@Api(tags = {"Feign-查询接口"})
@RequestMapping(value = "/api/point/query")
@RestController
public class HaierPointQueryApiOpenFeign implements HaierPointQueryApi {

    @Resource
    private ConfPlatformService service;

    @Resource
    private ConfActivityRuleApplyService confActivityRuleApplyService;

    @Resource
    private   PublMemberBalanceService publMemberBalanceService;

    @Resource
    private ConfPointCardService confPointCardService;





    @Resource
    private ConfPlatformApplyService confPlatformApplyService;

    @Resource
    private PublMemberLogService publMemberLogService;


    @Resource
    private ConfPlatformService confPlatformService;


    @Resource
    private ConfBdService confBdService;

    @Resource
    ConfBdApplyService confBdApplyService;

    @Resource
    private HaierSmartHomePointService haierSmartHomePointService;


    @Resource//第三方机构
    private ConfThirdPartService confThirdPartService;

    @Resource//供应闪
    private ConfSupplierService confSupplierService;

    @Resource//活动规则
    private ConfActivityRuleService confActivityRuleService;

    @Resource //用户
    private PublMemberService publMemberService;

    @Resource
    private ConfApiAuthorityService confApiAuthorityService;



    /**
     * @param request
     * @description: 查询海贝商城订单物流信息
     * @return: OrderQueryResponse
     * @author: fengrui
     * @time: 2020/11/25 17:18
     */
    @Override
    public RestResult<OrderQueryResponse> queryOrderCode(OrderQueryRequest request) {

        return null;
    }

    /**
     * @param request
     * @description: 冻结积分
     * @return: Boolean
     * @author: fengrui
     * @time: 2020/11/25 17:56
     */
    @Override
    public RestResult<Boolean> freezePoint(FreezePointRequest request) {
        if (request.getCode() == null)
            return RestResult.error("6666", "code不能为空");
        if (request.getCodeType() == null)
            return RestResult.error("6666", "编号类型不能为空不能为空");
        if (request.getSts() == null)
            return RestResult.error("6666", "冻结类型不能为空不能为空");
        if (request.getApplyReason() == null)
            return RestResult.error("6666", "冻结原因不能为空不能为空");
        if (request.getApplierId() == null)
            return RestResult.error("6666", "冻结人id不能为空不能为空");
        long flag = 0;
        switch (request.getCodeType()) {
            case "Member":


                break;
            case "Platform":
                ConfPlatform confPlatform = new ConfPlatform();
                confPlatform.setCode(request.getCode());
                ConfPlatform result = service.getByPrimaryCode(confPlatform);
                if (result == null) {
                    return RestResult.error("5555", "code错误");
                }
                //主表逻辑删除为1
                service.deleteByPrimaryKeyLogically(confPlatform);
                //赋值
                result.setSts(request.getSts());
                result.setApplyReason(request.getApplyReason());
                result.setApplierId(request.getApplierId());
                //插入到申请表
                ConfPlatformApply confPlatformApply = new ConfPlatformApply();
                BeanUtils.copyProperties(result, confPlatformApply);
                flag = confPlatformApplyService.insertSelective(confPlatformApply);
                break;
            case "Department":
                ConfBd confBd = new ConfBd();
                confBd.setCode(request.getCode());
                ConfBd bdresult = confBdService.getByPrimaryKey(confBd);
                if (bdresult == null) {
                    return RestResult.error("5555", "code错误");
                }
                //主表逻辑删除
                confBdService.deleteByPrimaryKeyLogically(bdresult);
                //将主表申请的信息添加到申请表中
                bdresult.setSts(request.getSts());
                bdresult.setApplyReason(request.getApplyReason());
                bdresult.setApplierId(request.getApplierId());

                //插入到申请表
                ConfBdApply confBdApply = new ConfBdApply();
                BeanUtils.copyProperties(bdresult, confBdApply);
                flag = confBdApplyService.insertSelective(confBdApply);
                break;
            case "Supplier":

                break;
            case "Activity_Rules":

                break;
            case "PointCard":

                break;
            default:
                return RestResult.error("5555", "没有此编号类型");
        }

        return RestResult.success(flag > 0);
    }

    /**
     * @description: 回收积分
     * @return: Boolean
     * @author: fengrui
     * @time: 2020/11/25 17:57
     */
    @Override
    public RestResult<Boolean> recyclePoint(RecyclePointRequest request) {
        return null;
    }

    /**
     * @param request
     * @description: 查询可用积分（对接积分中心）-内部方法（或web端）调用
     * @return: PlatformDudgetResponse
     * @author: fengrui
     * @time: 2020/11/25 17:19
     */
    @Override
    public RestResult<BigDecimal> querySurplusDudget(PlatformDudgetRequest request) {
        checkPointsReceive(request);
        checkPointsReceive2(request);

        BigDecimal availablePoint = null;
        if (request.getBusiType().equals("THRID_PART_PLATFORM")) { //第三方
            availablePoint = confThirdPartService.queryAvailablePoint(request.getBusiCode());
        } else if (request.getBusiType().equals("PLATFORM")) { //PLATFORM平台
            availablePoint = confPlatformService.queryAvailablePoint(request.getBusiCode());
        } else if (request.getBusiType().equals("ACTIVITY_RULE")) { //活动规则
            availablePoint = confActivityRuleApplyService.queryAvailablePoint(request.getBusiCode());
        } else if (request.getBusiType().equals("DEPARTMENT")) { //部门
            availablePoint = confBdService.queryAvailablePoint(request.getBusiCode());
        } else if (request.getBusiType().equals("SUPPLY")) { // 供应商
            availablePoint = confSupplierService.queryAvailablePoint(request.getBusiCode());
        }
        if (availablePoint==null){
            return RestResult.error("8888","没有相应的code");
        }

        return RestResult.success(availablePoint);
    }


    /**
     * @param request
     * @description: 活动提交接口（对接积分中心）-内部方法调用
     * @return: CommitRightsConfigRsponse
     * @author: fengrui
     * @time: 2020/11/25 17:20
     */
    @Override
    public RestResult<CommitRightsConfigRsponse> commitRightsConfig(CommitRightsConfigRequest request) {
        return null;
    }

    /**
     * @param request
     * @description: 查询流水
     * @return:
     * @author: fengrui
     * @time: 2020/11/28 14:17
     */
    @Override
    public RestResult<?> queryRunningWater(QueryRunningWaterRequest request) {
        checkPointsReceive(request);
        checkPointsReceive2(request);
        if (request.getBusiType().equals("THRID_PART_PLATFORM")) { //第三方
        } else if (request.getBusiType().equals("PLATFORM")) { //PLATFORM平台
        } else if (request.getBusiType().equals("ACTIVITY_RULE")) { //活动规则
        } else if (request.getBusiType().equals("DEPARTMENT")) { //部门
        } else if (request.getBusiType().equals("SUPPLY")) { // 供应商
        } else if (request.getBusiType().equals("MEMBER")){ //会员
            PublMemberBalanceFeignResponse  response = new PublMemberBalanceFeignResponse();
            PublMemberBalance member = new PublMemberBalance();
            member.setMemberCode(request.getBusiCode());
            //获取用户总积分，剩余积分，可用积分
            List<PublMemberBalanceResponse> publMemberBalanceResponses = publMemberBalanceService.queryMemberByCode(member);
            if (publMemberBalanceResponses==null){
                return RestResult.error("0001", "编号错误，并没有该用户");
            }
            PublMemberBalanceResponse balanceResponse = publMemberBalanceResponses.get(0);
            response.setAvailable(balanceResponse.getAvailable());
            response.setFrozen(balanceResponse.getFrozen());
            response.setTotal(balanceResponse.getTotal());

            PublMemberLog request1 = new PublMemberLog();
            BeanUtils.copyProperties(request,request1);
            request1.setMemberCode(request.getBusiCode());
            PageInfo<PublMemberLog> info = publMemberLogService.listPageBySelectiveTime(request1,request.getPageNum(),request.getPageSize(),null,null);
            List<QueryRunningWaterResponse> collect = info.getList().stream().map(item -> {
                QueryRunningWaterResponse queryRunningWaterResponse = new QueryRunningWaterResponse();
                BeanUtils.copyProperties(item, queryRunningWaterResponse);
                return queryRunningWaterResponse;
            }).collect(Collectors.toList());
            response.setList(collect);
            return RestResult.success(response);
        }


        return RestResult.error("6666","没有该类型的编号类型");
    }

    /**
     * @param request
     * @description: 活动审核接口（对接积分中心）-内部方法调用
     * @return: AuditRightsAndInterestsResponse
     * @author: fengrui
     * @time: 2020/11/25 17:53
     */
    @Override
    public RestResult<AuditRightsAndInterestsResponse> passRightsByRightsNo(AuditRightsAndInterestsRequest request) {
        return null;
    }

    /**
     * @param request
     * @description:
     * @return:
     * @author: fengrui
     * @time: 2020/11/25 17:53
     */
    @Override
    public RestResult<?> upperFindTotalPoint(UserAvailablePointRequest request) {
        return null;
    }

    /**
     *
     *
     * @description: 激活积分卡
     * @return:
     * @author: fengrui
     * @time: 2020/11/28 17:21
     */
    @Override
    @Transactional
    public RestResult<?> activateCardPoint(ActivateCardPointRequest request) {
        checkPointsReceive(request);
        checkPointsReceive2(request);
        List<ConfApiAuthority> confActivityRules = confApiAuthorityService.selConfActivityRuleByCode(request);
        if (confActivityRules==null) {
            return RestResult.error("0001", "编码错误，并没有该渠道");
        }
        if (confActivityRules.get(0).getProductType()==0) {
            return RestResult.error("0001", "该平台没有权限激活积分卡");
        }
        ConfPointCard confPointCard = new ConfPointCard();
        confPointCard.setCardNo(request.getCardNo());
        confPointCard.setCardPassword(request.getCardPassword());
        confPointCard.setMemberId(request.getMemberId());
        confPointCard.setMemberName(request.getMemberName());
        confPointCard.setMobileNo(request.getMobileNo());
        ConfPointCard result = confPointCardService.activateCardPoint(confPointCard);
        if (result==null){
            return RestResult.error("0001", "账号或者密码错误或者该积分卡已激活");
        }else if(result.getExpiryTime().before(new Date())){
            return RestResult.error("0001", "卡号已经过期");
        }
        confPointCard.setId(result.getId());
        confPointCard.setSts(2L);
        confPointCard.setActiveTime(new Date());
        confPointCard.setAvailable(new BigDecimal(0));
        confPointCardService.updateByPrimaryKeySelective(confPointCard);

        PublMemberBalance member = new PublMemberBalance();
        member.setMemberCode(request.getBusiCode());
        member.setAvailable(result.getAvailable());
        Integer add = publMemberBalanceService.addPoint(member);
        List<PublMemberBalanceResponse> publMemberBalanceResponses = publMemberBalanceService.queryMemberByCode(member);
        if (publMemberBalanceResponses!=null) {
            PublMemberLog log = new PublMemberLog();
            log.setMemberCode(request.getMemberCode());
            log.setType(1);
            log.setMemberCode(request.getBusiCode());
            log.setDeliveryType(1);
            log.setAmount(result.getAvailable());
            log.setDescription("用户激活积分卡");
            log.setCreateTime(new Date());
            log.setEarlyWarning(1);
            log.setThirdUserId(request.getMemberId().toString());
            int i = publMemberLogService.saveOrUpdate(log);
            if (i>0) {
                return RestResult.success(true);
            }
        }else{

        }

        return RestResult.error("0002", "激活失败");
    }

    /**
     * @param request
     * @description:
     * @return:
     * @author: fengrui
     * @time: 2020/11/25 17:54
     */
    @Override
    public RestResult<?> upperFindDataPoint(UserAvailableDetailRequest request) {
        return null;
    }


    //积分领取  校验主体  第一层校验
    public RestResult checkPointsReceive(SignData signData) {
        //查询参数业务类型和编码是否为空
        if (signData.getBusiType() != null && "".equals(signData.getBusiType()) && signData.getBusiCode() != null)
            return RestResult.error("0001", "业务类型或业务类型对应编码不能为空");
        //通过业务类型查询数据
        List<SignData> signData1 = haierSmartHomePointService.selAuthorityList(signData);
        if (signData1.size() < 1) return RestResult.error("0002", "当前操作，业务类型以及编码不存在");
        SignData sign = signData1.get(0);
        if (sign.getStatus() != 2) return RestResult.error("0003", "当前操作，渠道未启用！请先启用");
        if (sign.getAppKey() != null && sign.getSecreKey() != null) return RestResult.error("0004", "标识码和秘钥为空或不匹配");
        //判断是否有新增操作权限
        if (sign.getAddType() != 1) return RestResult.error("0005", "当前新增操作，无权限进行新增积分的操作！");
        return null;
    }

    //积分领取或消耗 第二层校验
    public RestResult checkPointsReceive2(SignData signData) {
        //如果新增 需要有相应的权限
        //如果是平台 必须有唯一绑定结算关系
        //调用接口的是BD，给某个部门增加或消耗积分时，必须要【1、预算关系】，不然不能新增/消耗积分；
        //  `sts` int(2) DEFAULT '0' COMMENT '状态（-3、双向冻结；-2、流入冻结，流出正常，-1、停用，0、初始化；1、启用；2、流入正常，流出冻结；）',
        //第三方机构校验
        if ("THRID_PART_PLATFORM".equals(signData.getBusiType())) {
            List<ConfThirdPart> confThirdParts = confThirdPartService.selThirdPartByCode(signData);
            if (confThirdParts.size() < 1) return RestResult.error("0011", "第三方机构编码有误或不存在！");
            ConfThirdPart confThirdPart = confThirdParts.get(0);
            if (confThirdPart.getSts() == -3) return RestResult.error("0012", "当前第三方机构，状态有误");
            if (confThirdPart.getAuditFlag() == 0) return RestResult.error("0013", "当前第三方机构，未启用");
            if (confThirdPart.getAuditSts() != 1) return RestResult.error("0014", "当前第三方机构，未审核通过");
        }
        //平台校验
        if ("PLATFORM".equals(signData.getBusiType())) {
            List<ConfPlatform> confPlatforms = service.selectByPrimaryCode(signData);
            if (confPlatforms.size() < 1) return RestResult.error("0011", "平台编码有误或不存在！");
            ConfPlatform confPlatform = confPlatforms.get(0);
            if (confPlatform.getSts() == -3) return RestResult.error("0012", "当前平台，状态有误");
            if (confPlatform.getAuditFlag() == 0) return RestResult.error("0013", "当前平台，未启用");
            if (confPlatform.getAuditSts() != 1) return RestResult.error("0014", "当前平台，未审核通过");
        }
        //部门校验
        if ("DEPARTMENT".equals(signData.getBusiType())) {
            List<ConfBd> confBds = confBdService.selConfBdByCode(signData);
            if (confBds.size() < 1) return RestResult.error("0011", "部门编码有误或不存在！");
            ConfBd confBd = confBds.get(0);
            if (confBd.getSts() == -3) return RestResult.error("0012", "当前部门，状态有误");
            if (confBd.getAuditSts() != 1) return RestResult.error("0014", "当前部门，未审核通过");
        }
        //供应商
        if ("SUPPLY".equals(signData.getBusiType())) {
            List<ConfSupplier> confSuppliers = confSupplierService.selConfSupplierByCode(signData);
            if (confSuppliers.size() < 1) return RestResult.error("0011", "供应商编码有误或不存在！");
            ConfSupplier confSupplier = confSuppliers.get(0);
            if (confSupplier.getSts() == -3) return RestResult.error("0012", "当前供应商，状态有误");
            if (confSupplier.getAuditSts() != 1) return RestResult.error("0014", "当前供应商，未审核通过");
        }
        //活动规则
        if ("ACTIVITY_RULE".equals(signData.getBusiType())) {
            List<ConfActivityRule> confActivityRules = confActivityRuleService.selConfActivityRuleByCode(signData);
            if (confActivityRules.size() < 1) return RestResult.error("0011", "活动规则编码有误或活动规则不存在！");
            ConfActivityRule confActivityRule = confActivityRules.get(0);
            if (confActivityRule.getSts() == -3) return RestResult.error("0012", "当前活动规则，状态有误");
            if (confActivityRule.getAuditSts() != 1) return RestResult.error("0014", "当前活动规则，未审核通过");
        }
        return null;
    }

}
